<template>
    <el-dialog v-model="visible" :title="title" width="900px" :before-close="handleClose"
        class="member-selector-dialog">
        <div class="dialog-container">
            <!-- 左侧：已选择成员面板 -->
            <div class="selected-panel">
                <div class="panel-header">
                    <span class="panel-title">已选择成员</span>
                    <div class="count-badge">{{ selectedMembers.length }}/{{ maxSelect }}</div>
                    <el-button v-if="selectedMembers.length > 0" type="danger" text @click="clearAllSelected"
                        size="small">
                        清空
                    </el-button>
                </div>
                <div class="selected-list">
                    <div v-if="selectedMembers.length === 0" class="empty-hint">
                        <el-icon>
                            <InfoFilled />
                        </el-icon>
                        <span>暂无选择成员</span>
                    </div>
                    <div v-else class="member-cards">
                        <div v-for="member in selectedMembers" :key="member.id" class="member-card">
                            <div class="member-info">
                                <el-icon class="member-icon" :class="member.type">
                                    <component :is="getMemberIcon(member.type)" />
                                </el-icon>
                                <div>
                                    <div class="member-name">{{ member.name }}</div>
                                    <div class="member-type">{{ getTypeName(member.type) }}</div>
                                </div>
                            </div>
                            <el-button circle size="small" @click="removeSelected(member)">
                                <el-icon>
                                    <Close />
                                </el-icon>
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧：组织结构和选择面板 -->
            <div class="selection-panel">
                <!-- 搜索栏 -->
                <div class="search-bar">
                    <el-input v-model="searchQuery" placeholder="搜索成员或部门..." clearable @clear="handleSearchClear"
                        @keyup.enter="handleSearch">
                        <template #prefix>
                            <el-icon>
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                </div>

                <!-- 导航路径 -->
                <div class="navigation-path">
                    <el-breadcrumb separator="/">
                        <el-breadcrumb-item v-for="(item, index) in navigationPath" :key="index"
                            @click="navigateTo(index)" class="breadcrumb-item">
                            <el-icon v-if="index === 0">
                                <HomeFilled />
                            </el-icon>
                            {{ item.name }}
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>

                <!-- 成员列表 -->
                <div class="member-list">
                    <el-scrollbar height="400px">
                        <div v-if="loading" class="loading-container">
                            <el-icon class="loading-icon">
                                <Loading />
                            </el-icon>
                            <span>加载中...</span>
                        </div>

                        <div v-else-if="currentList.length === 0" class="empty-list">
                            <el-icon>
                                <FolderDelete />
                            </el-icon>
                            <span>当前目录为空</span>
                        </div>

                        <div v-else class="list-container">
                            <div v-for="item in currentList" :key="item.id" class="list-item"
                                :class="{ 'is-selected': isSelected(item), 'is-selectable': isSelectable(item) }"
                                @click="handleItemClick(item)">
                                <div class="item-content">
                                    <el-icon class="item-icon" :class="item.type">
                                        <component :is="getMemberIcon(item.type)" />
                                    </el-icon>
                                    <div class="item-info">
                                        <div class="item-name">{{ item.name }}</div>
                                        <div class="item-description">{{ item.description }}</div>
                                    </div>
                                </div>
                                <el-button v-if="isSelectable(item)" type="primary" size="small"
                                    :class="{ 'selected-button': isSelected(item) }" @click.stop="toggleSelect(item)">
                                    {{ isSelected(item) ? '已选择' : '选择' }}
                                </el-button>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
        </div>

        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确定选择</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, defineProps, defineEmits } from 'vue'
import {
    Search,
    Close,
    HomeFilled,
    InfoFilled,
    Loading,
    FolderDelete,
    OfficeBuilding,
    House,
    Suitcase,
    User
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    title: {
        type: String,
        default: '选择组织成员'
    },
    visible: {
        type: Boolean,
        default: false
    },
    maxSelect: {
        type: Number,
        default: Infinity
    },
    selectType: {
        type: String,
        default: 'employee',
        validator: (value) => ['employee', 'department'].includes(value)
    },
    initialSelected: {
        type: Array,
        default: () => []
    }
})

const emit = defineEmits(['update:visible', 'confirm'])

// 数据状态
const loading = ref(false)
const searchQuery = ref('')
const selectedMembers = ref([...props.initialSelected])
const navigationPath = ref([
    { id: 'root', name: '全部组织', type: 'root', children: [] }
])

// 当前显示的列表
const currentList = ref([])

// 组织数据 (模拟数据)
const organizationData = reactive({
    companies: [
        {
            id: 'company-1',
            name: '总公司',
            type: 'company',
            description: '集团总部',
            children: [
                {
                    id: 'branch-1',
                    name: '华东分公司',
                    type: 'branch',
                    description: '华东地区分公司',
                    children: [
                        {
                            id: 'dept-1',
                            name: '研发部',
                            type: 'department',
                            description: '技术研发部门',
                            children: [
                                {
                                    id: 'emp-1',
                                    name: '张三',
                                    type: 'employee',
                                    description: '前端工程师'
                                },
                                {
                                    id: 'emp-2',
                                    name: '李四',
                                    type: 'employee',
                                    description: '后端工程师'
                                }
                            ]
                        },
                        {
                            id: 'dept-2',
                            name: '市场部',
                            type: 'department',
                            description: '市场营销部门',
                            children: [
                                {
                                    id: 'emp-3',
                                    name: '王五',
                                    type: 'employee',
                                    description: '市场经理'
                                }
                            ]
                        }
                    ]
                },
                {
                    id: 'branch-2',
                    name: '华南分公司',
                    type: 'branch',
                    description: '华南地区分公司',
                    children: [
                        {
                            id: 'dept-3',
                            name: '销售部',
                            type: 'department',
                            description: '销售团队',
                            children: [
                                {
                                    id: 'emp-4',
                                    name: '赵六',
                                    type: 'employee',
                                    description: '销售主管'
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        {
            id: 'company-2',
            name: '子公司A',
            type: 'company',
            description: '全资子公司',
            children: [
                {
                    id: 'dept-4',
                    name: '财务部',
                    type: 'department',
                    description: '财务管理',
                    children: [
                        {
                            id: 'emp-5',
                            name: '钱七',
                            type: 'employee',
                            description: '财务总监'
                        }
                    ]
                }
            ]
        }
    ]
})

// 计算属性
const visible = computed({
    get() {
        return props.visible
    },
    set(value) {
        emit('update:visible', value)
    }
})

// 方法
const loadCurrentList = () => {
    loading.value = true
    // 模拟异步加载
    setTimeout(() => {
        const current = navigationPath.value[navigationPath.value.length - 1]

        if (current.id === 'root') {
            currentList.value = [...organizationData.companies]
        } else {
            let children = []

            if (current.type === 'company') {
                const company = organizationData.companies.find(c => c.id === current.id)
                children = company ? company.children : []
            } else if (current.type === 'branch') {
                for (const company of organizationData.companies) {
                    const branch = company.children.find(b => b.id === current.id)
                    if (branch) {
                        children = branch.children
                        break
                    }
                }
            } else if (current.type === 'department') {
                for (const company of organizationData.companies) {
                    for (const branch of company.children) {
                        const dept = branch.children.find(d => d.id === current.id)
                        if (dept) {
                            children = dept.children
                            break
                        }
                    }
                }
            }

            currentList.value = [...children]
        }

        loading.value = false
    }, 300)
}

const getMemberIcon = (type) => {
    switch (type) {
        case 'company': return OfficeBuilding
        case 'branch': return House
        case 'department': return Suitcase
        case 'employee': return User
        default: return User
    }
}

const getTypeName = (type) => {
    switch (type) {
        case 'company': return '公司'
        case 'branch': return '分公司'
        case 'department': return '部门'
        case 'employee': return '员工'
        default: return '成员'
    }
}

const navigateTo = (index) => {
    if (index === navigationPath.value.length - 1) return
    navigationPath.value = navigationPath.value.slice(0, index + 1)
    loadCurrentList()
}

const handleItemClick = (item) => {
    if (item.type === 'employee' && props.selectType !== 'employee') return

    if (item.children && item.children.length > 0) {
        navigationPath.value.push(item)
        loadCurrentList()
    }
}

const isSelectable = (item) => {
    if (props.selectType === 'employee') {
        return item.type === 'employee'
    } else {
        return item.type === 'department'
    }
}

const isSelected = (item) => {
    return selectedMembers.value.some(m => m.id === item.id)
}

const toggleSelect = (item) => {
    if (isSelected(item)) {
        removeSelected(item)
    } else {
        if (selectedMembers.value.length >= props.maxSelect) {
            ElMessage.warning(`最多只能选择 ${props.maxSelect} 个`)
            return
        }
        addSelected(item)
    }
}

const addSelected = (item) => {
    selectedMembers.value.push({
        id: item.id,
        name: item.name,
        type: item.type,
        description: item.description
    })
}

const removeSelected = (item) => {
    selectedMembers.value = selectedMembers.value.filter(m => m.id !== item.id)
}

const clearAllSelected = () => {
    selectedMembers.value = []
}

const handleSearch = () => {
    // 实现搜索功能
    ElMessage.info('搜索功能待实现')
}

const handleSearchClear = () => {
    searchQuery.value = ''
    loadCurrentList()
}

const handleClose = () => {
    visible.value = false
}

const handleConfirm = () => {
    emit('confirm', [...selectedMembers.value])
    visible.value = false
}

// 监听
watch(visible, (val) => {
    if (val) {
        navigationPath.value = [{ id: 'root', name: '全部组织', type: 'root', children: [] }]
        loadCurrentList()
    }
})

watch(() => props.initialSelected, (newVal) => {
    selectedMembers.value = [...newVal]
}, { deep: true })
</script>

<style lang="less" scoped>
.member-selector-dialog {
    .dialog-container {
        display: flex;
        height: 500px;
        gap: 16px;

        .selected-panel {
            width: 280px;
            border-right: 1px solid var(--el-border-color);
            display: flex;
            flex-direction: column;

            .panel-header {
                display: flex;
                align-items: center;
                padding: 8px 12px;
                border-bottom: 1px solid var(--el-border-color);

                .panel-title {
                    font-weight: bold;
                    margin-right: 8px;
                }

                .count-badge {
                    background-color: var(--el-color-primary-light-9);
                    color: var(--el-color-primary);
                    padding: 2px 8px;
                    border-radius: 10px;
                    font-size: 12px;
                    margin-right: auto;
                }
            }

            .selected-list {
                flex: 1;
                overflow-y: auto;
                padding: 8px;

                .empty-hint {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    height: 100%;
                    color: var(--el-text-color-secondary);

                    .el-icon {
                        font-size: 48px;
                        margin-bottom: 12px;
                        color: var(--el-text-color-placeholder);
                    }
                }

                .member-cards {
                    display: flex;
                    flex-direction: column;
                    gap: 8px;

                    .member-card {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 8px 12px;
                        background-color: var(--el-bg-color);
                        border-radius: 4px;
                        border: 1px solid var(--el-border-color-light);

                        .member-info {
                            display: flex;
                            align-items: center;

                            .member-icon {
                                margin-right: 8px;
                                font-size: 20px;

                                &.company {
                                    color: var(--el-color-primary);
                                }

                                &.branch {
                                    color: var(--el-color-success);
                                }

                                &.department {
                                    color: var(--el-color-warning);
                                }

                                &.employee {
                                    color: var(--el-color-info);
                                }
                            }

                            .member-name {
                                font-weight: 500;
                            }

                            .member-type {
                                font-size: 12px;
                                color: var(--el-text-color-secondary);
                            }
                        }
                    }
                }
            }
        }

        .selection-panel {
            flex: 1;
            display: flex;
            flex-direction: column;

            .search-bar {
                padding-bottom: 12px;

                .el-input {
                    :deep(.el-input__wrapper) {
                        padding-left: 10px;
                    }
                }
            }

            .navigation-path {
                padding: 8px 0;

                .breadcrumb-item {
                    display: inline-flex;
                    align-items: center;
                    cursor: pointer;

                    &:hover {
                        color: var(--el-color-primary);
                    }

                    .el-icon {
                        margin-right: 4px;
                    }
                }
            }

            .member-list {
                flex: 1;

                .loading-container,
                .empty-list {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    height: 100%;
                    color: var(--el-text-color-secondary);

                    .el-icon {
                        font-size: 48px;
                        margin-bottom: 12px;
                        color: var(--el-text-color-placeholder);
                    }
                }

                .list-container {
                    .list-item {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 12px;
                        margin-bottom: 8px;
                        border-radius: 4px;
                        cursor: pointer;
                        transition: all 0.2s;

                        &:hover {
                            background-color: var(--el-color-primary-light-9);
                        }

                        &.is-selected {
                            background-color: var(--el-color-primary-light-8);
                        }

                        &.is-selectable:hover {
                            background-color: var(--el-color-primary-light-9);
                        }

                        .item-content {
                            display: flex;
                            align-items: center;

                            .item-icon {
                                margin-right: 12px;
                                font-size: 24px;

                                &.company {
                                    color: var(--el-color-primary);
                                }

                                &.branch {
                                    color: var(--el-color-success);
                                }

                                &.department {
                                    color: var(--el-color-warning);
                                }

                                &.employee {
                                    color: var(--el-color-info);
                                }
                            }

                            .item-info {
                                .item-name {
                                    font-weight: 500;
                                    margin-bottom: 4px;
                                }

                                .item-description {
                                    font-size: 12px;
                                    color: var(--el-text-color-secondary);
                                }
                            }
                        }

                        .selected-button {
                            background-color: var(--el-color-primary);
                            color: white;
                        }
                    }
                }
            }
        }
    }
}
</style>
